//
//  ChangeLogoController.m
//  NPS
//
//  Created by jadd on 15/10/14.
//  Copyright © 2015年 jadd. All rights reserved.
//

#import "ChangeLogoController.h"

@interface ChangeLogoController ()

@property (nonatomic, strong) UIActionSheet *action;

@property (nonatomic,strong) UIImageView *image;
@end


@implementation ChangeLogoController
@synthesize logoImageView;
@synthesize height,width;

-(void)backButtonPressed{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void) setUpView
{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight - 70)];
    footView.backgroundColor = CLEAR;
    
    UILabel *lable = [[UILabel alloc] init];
    lable.textColor = GRAY;
    lable.adjustsFontSizeToFitWidth = YES;
    lable.font = [UIFont systemFontOfSize:15];
    lable.text = @"企业Logo将出现在问卷网的左上方，效果如下";
    
    [footView addSubview:lable];
    //top left bottom right
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.height.equalTo(@150);
        make.top.offset(5);
        //make.centerY.equalTo(footView.mas_top);
        make.left.offset(20);
        make.right.offset(-20);
        
    }];
    
    UIImageView *imagebg = [[UIImageView alloc] init];
    imagebg.tintColor = CLEAR;
    imagebg.autoresizesSubviews = YES;
    [footView addSubview:imagebg];
    [imagebg setImage:[UIImage imageNamed:@"muban"]];
    [imagebg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(30);
        make.left.offset(5);
        make.right.offset(-5);
        
    }];
    

    logoImageView = [[UIImageView alloc] init];
    logoImageView.backgroundColor = [UIColor redColor];
    

    //[logoImageView setImageWithURL:[MyGlobal sharedVariables].logoUrl];
    logoImageView.clipsToBounds = YES;
    
    
    logoImageView.contentMode =  UIViewContentModeScaleAspectFill;
    //logoImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
//    logoImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [imagebg addSubview:logoImageView];
    [logoImageView mas_makeConstraints:^(MASConstraintMaker  *make) {
        make.size.mas_equalTo(CGSizeMake(170, 35));
        make.top.offset(25);
        make.left.offset(40);
        //make.right.offset(-5);
        
    }];
    [self.tableView setTableFooterView:footView];
}
- (void)viewDidLoad {
    //self.edgesForExtendedLayout = UIRectEdgeNone;

    self.title = @"更换logo";

    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom] ;
    button.frame = CGRectMake(0, 0, K_Global_BackButton_Width, K_Global_BackButton_Height);
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button setImage:[UIImage imageNamed:@"back_white_on"] forState:UIControlStateNormal];
    //[button setImage:[UIImage imageNamed:@"back_white_on"] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftButton;

    self.height = 50;
    self.width = 50;
    //右边滚动条是否显示
    [self.tableView setShowsVerticalScrollIndicator:NO];
    [self setUpView];
    [super viewDidLoad];
    
}

-(void)viewDidDisappear:(BOOL)animated
{
   
    [super viewDidDisappear:animated];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 55;
}



-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    //NSLog(@"%f",K_ScreenHeight - 100);
    if(section == 0)
        return 0 ;
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString *identifier = @"TJCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
        

    }
    
    CGRect rect = CGRectMake((K_ScreenWidth/320)*120, 10, 170, 35);
    //[self.image setFrame:rect];
    
    self.image = [[UIImageView alloc] init];
    [self.image setFrame:rect];
    
    self.image.userInteractionEnabled = YES;
    
    
    
    //[self.image setImageWithURL:[MyGlobal sharedVariables].logoUrl placeholderImage:[UIImage imageNamed:@"dianpu"]];
    
    self.image.clipsToBounds = YES;
    //self.image.contentMode =  UIViewContentModeRight;
    self.image.contentMode =  UIViewContentModeScaleAspectFit;
    //self.image.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    
    //[self.image setImage:image];
    [cell.contentView addSubview:self.image];
    
    
    cell.textLabel.text = @"企业Logo";
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 255) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            switch(buttonIndex)
            {
                case 2://取消
                    return;
                case 1://相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 0: //相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                default:
                    return;
            }
        }
        else
        {
            if(buttonIndex == 1){
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    NSData *data = UIImagePNGRepresentation(image);
    
    [self uploadImage:data Image:image];
    
    
}


- (void)chooseImagePressed {
    UIActionSheet *sheet;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取 消" destructiveButtonTitle:nil otherButtonTitles:@"从相册中选取",@"拍照", nil];
    } else {
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取 消" destructiveButtonTitle:nil otherButtonTitles:@"从相册中选取", nil];
    }
    sheet.tag = 255;
    [sheet showInView:self.view];
}


#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        [self chooseImagePressed];
    }
}



-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

-(void) uploadImage:(NSData *) imageData Image:(UIImage *)image
{
    [Config showActivityView];
    ChangeLogoRequest * request = [[ChangeLogoRequest alloc] initWithUserId:[Config getUser_id]];
    [RequestHandle uplaodImageOperationWithRequest:request uploadData:imageData complete:^(id responseObject) {
        
        
        
        ChangeLogoResponse * response = [[ChangeLogoResponse alloc] init];
        response.responseObject = responseObject;
        
        if([[responseObject objectForKey:@"status"] isEqualToString:@"success"])
        {
            
            //[Config showMessage:@"更换成功"];
//
            //CGSize size = {170 ,35};
            
            
            
            self.height = 35;
            self.width = 170;
            
            
            [Config hideActivityView];
            
            [self.tableView reloadData];
        }
        while (![[NSUserDefaults standardUserDefaults] synchronize]) {}
        
        
        
    } error:^(NSError *error) {
        //NSLog(@"%@",error);
        if(error.code == ERROR_PARA_VERIFIY){
            RepeatLoginController *controller = [[RepeatLoginController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
            controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            [self presentViewController:nav animated:YES completion:^{
                NSLog(@"");
            }];
        }
        else{
            [Config showMessage:error.localizedDescription];
        }
        
    }];

}

@end
